//
//  HJChatMessageImageCell.m
//  XWC
//
//  Created by Hello on 2022/10/25.
//

#import "HJChatMessageImageCell.h"
#import "HJChatMessageImageLayout.h"
#import "HJChatMessageModel.h"
#import "HJProgressMarkView.h"
#import "TUIDefine.h"
#import "HJIM.h"

@interface HJChatMessageImageCell()

@property (nonatomic, weak) HJProgressMarkView *progressMarkView;


@end


@implementation HJChatMessageImageCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.bubbleView.clipsToBounds = YES;
        UIImageView *imageView = [UIImageView addToView:self.bubbleView];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        _contentImageView = imageView;
        imageView.layer.masksToBounds = YES;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateChatFileUploadProgressNotification:) name:updateChatFileUploadProgressNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdateChatThumbnailPathNotification:) name:updateChatThumbnailPathNotification object:nil];
        
        _progressMarkView = [HJProgressMarkView addToView:self.bubbleView];
        _progressMarkView.progress = 0;
        _progressMarkView.hidden = YES;
        
    }
    return self;
}

 
- (void)layoutSubviews {
    [super layoutSubviews];
    
    _contentImageView.frame = CGRectMake(0, 0, self.messageLayout.containerViewRect.size.width, self.messageLayout.containerViewRect.size.height);
    _progressMarkView.frame = _contentImageView.bounds;
}

- (void)setMessageLayout:(HJChatMessageLayout *)messageLayout {
    [super setMessageLayout:messageLayout];
    
    if (TJIM_isSelf(messageLayout.messageModel.senderId)) {
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:messageLayout.messageModel.thumbnailPath]) {
            _contentImageView.image = [UIImage imageWithContentsOfFile:messageLayout.messageModel.thumbnailPath];
        } else {
            if (isEmptyString(messageLayout.messageModel.thumbnailUrl)) {
                _contentImageView.image = [UIImage imageNamed:loadImageDefaultImageName];
                [self makeThumbnailWithImage:nil];
            } else {
                [_contentImageView tj_setImageWithURL:messageLayout.messageModel.thumbnailUrl.URL placeholderImage:[UIImage imageNamed:loadImageDefaultImageName]];
            }
        }
        if (messageLayout.messageModel.msgStatus == HJMessageStatusSending) {
            [self.progressMarkView startAnimating];
            [self updateProgress:messageLayout.messageModel.progress];
        } else {
            [_progressMarkView stopAnimating];
        }
        
    } else {
        if (messageLayout.messageModel.imageloadStatus == HJImageLoadStatusSucceed) {
            [self.progressMarkView stopAnimating];
        } else {
            [self.progressMarkView startAnimating];
            [self updateProgress:messageLayout.messageModel.progress];
        }
     
        TJWeakify(self)
        [_contentImageView tj_setImageWithURL:messageLayout.messageModel.thumbnailUrl.URL placeholderImage:[UIImage imageNamed:loadImageDefaultImageName] progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            dispatch_async_main_queue(^{
                if ([targetURL.absoluteString isEqualToString:messageLayout.messageModel.thumbnailUrl]) {
                    if (expectedSize > 0) {
                        [weakself updateProgress:receivedSize / (expectedSize * 1.0)];
                    }
                }
            });
        } completed:^(UIImage * _Nullable image, SDImageCacheType cacheType) {
            [weakself.progressMarkView stopAnimating];
            
            if (image && image.size.width) {
                if (messageLayout.messageModel.imageloadStatus != HJImageLoadStatusSucceed) {
                    messageLayout.messageModel.imageloadStatus = HJImageLoadStatusSucceed;
                    [messageLayout.messageModel bg_saveOrUpdateAsync:nil];
                }
            } else {
                messageLayout.messageModel.imageloadStatus = HJImageLoadStatusFail;
            }
        }];
      
    }
    
}


- (void)makeThumbnailWithImage:(nullable UIImage *)image {
    HJChatMessageModel *messageModel = self.messageLayout.messageModel;
    if (TJIM_isSelf(messageModel.senderId)) {
        
        void (^saveThumbnailImage)(UIImage *originImage) = ^(UIImage *originImage) {
            
            CGSize thumbnailImageSize = getThumbnailImageSize(originImage.size, TImageMessageCell_Image_Width_Max);
            UIImage *thumbnailImage = [originImage imageSize:thumbnailImageSize color:UIColor.whiteColor];
            [HJTools writeIMImage:thumbnailImage toLocalPath:messageModel.thumbnailPath];
            [messageModel bg_saveOrUpdateAsync:nil];
            dispatch_async_main_queue(^{
                [[NSNotificationCenter defaultCenter] postNotificationName:updateChatThumbnailPathNotification object:messageModel];
            });
        };
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:messageModel.localPath]) {
            dispatch_async_serial_queue(^{
                UIImage *originImage = [UIImage imageWithContentsOfFile:messageModel.localPath];
                saveThumbnailImage(originImage);
            });
        } else { //下载
            [HJIM.shareIM.chatManager getOriginalImageWithMessageWithModel:messageModel completion:^(UIImage * _Nullable image) {
                if (image && image.size.width > 0) {
                    dispatch_async_serial_queue(^{
                        saveThumbnailImage(image);
                    });
                }
            }];
        }
    } else {
        dispatch_async_serial_queue(^{
            NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
            if (imageData.length > 1024 * 25) {
                NSString *cacheKey = [[SDWebImageManager sharedManager] cacheKeyForURL:messageModel.thumbnailUrl.URL];
                NSString *path = [[SDImageCache sharedImageCache] cachePathForKey:cacheKey];
                if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                    NSString *thumbnailPath = messageModel.thumbnailPath;
                    if (![[NSFileManager defaultManager] fileExistsAtPath:thumbnailPath]) {
                        NSData *thumbnailImageData = getThumbnailWithImage(image, CGSizeMake(TImageMessageCell_Image_Width_Max, TImageMessageCell_Image_Height_Max));
                        if (thumbnailImageData.length > 25 * 1024) {
                            thumbnailImageData = [UIImage compressWithImage:[UIImage imageWithData:thumbnailImageData] toByte:25];
                        }
                        [HJTools writeImageData:thumbnailImageData toLocalPath:thumbnailPath];
                    }
                }
            }
        });
    }
}

- (void)updateProgress:(CGFloat)progress {
    progress = progress > 0 ? progress : 0;
    
    self.messageLayout.messageModel.progress = progress;
    self.progressMarkView.progress = progress;
}

- (void)handleUpdateChatThumbnailPathNotification:(NSNotification *)not {
    HJChatMessageModel *messageModel = not.object;
    
    if (![messageModel.msg isEqualToString:self.messageLayout.messageModel.msgId]) return;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:messageModel.thumbnailPath]) {
        _contentImageView.image = [UIImage imageWithContentsOfFile:messageModel.thumbnailPath];
    }
}

- (void)handleUpdateChatFileUploadProgressNotification:(NSNotification *)not {
    NSDictionary *info = not.object;
    
    NSString *msgId = info[@"msgId"];
    CGFloat progress = [info[@"progress"] floatValue];
    if (![msgId isEqualToString:self.messageLayout.messageModel.msgId]) return;
    [self updateProgress:progress];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
